#include "stdafx.h"
#include "D3D_Utilities.h"
#include <D3D10.h>
#include <D3DX10.h>

namespace Utilities
{
	namespace D3D
	{
		void Inverse(Matrix44f &anInvertedMatrix, Matrix44f &aMatrix)
		{
			D3DXMATRIX orgMatrix(
				aMatrix[0],  aMatrix[1],  aMatrix[2],  aMatrix[3],
				aMatrix[4],  aMatrix[5],  aMatrix[6],  aMatrix[7],
				aMatrix[8],  aMatrix[9],  aMatrix[10], aMatrix[11],
				aMatrix[12], aMatrix[13], aMatrix[14], aMatrix[15]);
			D3DXMATRIX invMatrix(
				1.0f, 0.0f, 0.0f, 0.0f,
				0.0f, 1.0f, 0.0f, 0.0f,
				0.0f, 0.0f, 1.0f, 0.0f,
				0.0f, 0.0f, 0.0f, 1.0f);
			D3DXMatrixInverse(&invMatrix,NULL,&orgMatrix);
			anInvertedMatrix.ConvertD3D(static_cast<float*>(&invMatrix[0]));
		}

		void MatrixLookAt(Matrix44f &aMatrix, const Vector3f &aPosition, const Vector3f &aTarget, const Vector3f &anUp)
		{
			D3DXMATRIX mat;
			const D3DXVECTOR3 *eye = reinterpret_cast<const D3DXVECTOR3*>(&aPosition.x);
			const D3DXVECTOR3 *at = reinterpret_cast<const D3DXVECTOR3*>(&aTarget.x);
			const D3DXVECTOR3 *up = reinterpret_cast<const D3DXVECTOR3*>(&anUp.x);
			D3DXMatrixLookAtLH(&mat, eye, at, up);
			aMatrix.Init(&mat[0]);
		}

		void MatrixLookAt(Matrix33f &aMatrix, const Vector3f &aPosition, const Vector3f &aTarget, const Vector3f &anUp)
		{
			D3DXMATRIX mat;
			const D3DXVECTOR3 *eye = reinterpret_cast<const D3DXVECTOR3*>(&aPosition.x);
			const D3DXVECTOR3 *at = reinterpret_cast<const D3DXVECTOR3*>(&aTarget.x);
			const D3DXVECTOR3 *up = reinterpret_cast<const D3DXVECTOR3*>(&anUp.x);
			D3DXMatrixLookAtLH(&mat, eye, at, up);
			for (unsigned int j=0; j<3; ++j)
			{
				for (unsigned int i=0; i<3; ++i)
				{
					aMatrix[i+3*j] = mat[i+4*j];
				}
			}
		}

		void MatrixPerspective(Matrix44f &aMatrix, const float &aYFov, const float &someAspects, const float &aNearPlane, const float &aFarPlane)
		{
			D3DXMATRIX projection;
			D3DXMatrixPerspectiveFovLH(&projection, aYFov, someAspects, aNearPlane, aFarPlane);
			aMatrix.Init(static_cast<float*>(projection));
		}

		void MatrixOrthographic(Matrix44f &aMatrix, const float &aWidth, const float &aHeight, const float &aNearPlane, const float &aFarPlane)
		{
			D3DXMATRIX projection;
			D3DXMatrixOrthoLH(&projection, aWidth, aHeight, aNearPlane, aFarPlane);
			aMatrix.Init(static_cast<float*>(projection));
		}

		void MatrixOrthographic(Matrix44f &aMatrix, const Vector3f &aMinPoint, const Vector3f &aMaxPoint)
		{
			D3DXMATRIX projection;
			D3DXMatrixOrthoOffCenterLH(&projection, aMinPoint.x, aMaxPoint.x, aMinPoint.y, aMaxPoint.y, aMinPoint.z, aMaxPoint.z);
			aMatrix.Init(static_cast<float*>(projection));
		}
	};
};